﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using ETask.Api.Dtos;

namespace ETask.Api.Data
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var exception = context.Exception;

            _logger.LogError(exception, "发生未处理异常");

            (int statusCode, string message) = exception switch
            {
                KeyNotFoundException ex => (StatusCodes.Status404NotFound, ex.Message),
                UnauthorizedAccessException ex => (StatusCodes.Status403Forbidden, ex.Message),
                _ => (StatusCodes.Status500InternalServerError, "服务器内部错误，请稍后重试")
            };

          
            var result = new ObjectResult(ApiResponse.Fail(statusCode,message))
            {
                StatusCode = statusCode
            };
            context.Result = result;
            context.ExceptionHandled = true; 
        }
    }

}
